package service

import (
	"io"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/mux"
)

// Message type
type Message struct {
	CommonName   string
	Organization string
	PubKeyData   string
}

// var mutex = &sync.Mutex{}

// var contract Contract

// SmartContractServer type.
type SmartContractServer struct {
}

// Run function
func (bs *SmartContractServer) Run() error {
	mux := bs.makeMuxRouter()
	httpPort := Config.Port
	// httpPort := "18004"
	log.Println("合约服务器正在监听端口:", httpPort)
	s := &http.Server{
		Addr:           ":" + string(httpPort),
		Handler:        mux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	log.Println(s.Addr)

	if err := s.ListenAndServe(); err != nil {
		return err
	}

	return nil
}

// create handlers
func (bs *SmartContractServer) makeMuxRouter() http.Handler {
	muxRouter := mux.NewRouter()
	muxRouter.HandleFunc("/query", bs.handleQuery).Methods("GET")
	muxRouter.HandleFunc("/invoke", bs.handleInvoke).Methods("GET")
	// muxRouter.HandleFunc("/registry", bs.handleRegistry).Methods("POST")
	return muxRouter
}

func (bs *SmartContractServer) handleQuery(w http.ResponseWriter, r *http.Request) {
	// pemName := "pubkey.pem"
	// w.Header().Set("Content-Type", "application/octet-stream")
	// w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", pemName))
	// bytes := bs.manager.GetSystemPublicKey()
	// io.WriteString(w, string(bytes))

	// bytes, err := json.MarshalIndent(Blockchain, "", "  ")
	// if err != nil {
	// 	http.Error(w, err.Error(), http.StatusInternalServerError)
	// 	return
	// }
	io.WriteString(w, "")
}

func (bs *SmartContractServer) handleInvoke(w http.ResponseWriter, r *http.Request) {
	// pemName := "pubkey.pem"
	// w.Header().Set("Content-Type", "application/octet-stream")
	// w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", pemName))
	// bytes := bs.manager.GetSystemPublicKey()
	// io.WriteString(w, string(bytes))

	// bytes, err := json.MarshalIndent(Blockchain, "", "  ")
	// if err != nil {
	// 	http.Error(w, err.Error(), http.StatusInternalServerError)
	// 	return
	// }
	io.WriteString(w, "")
}
